<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                <el-select v-model="queryParams.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')">
                    <el-option v-for="dict in typesList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
                    $t('common.button.query') }}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.button.reset')
                }}</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:manual:add']">{{ $t('common.button.add') }}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:manual:edit']">{{ $t('common.button.edit') }}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:manual:remove']">{{ $t('common.button.remove') }}</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="manualList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column :label="$t('vehicle.type.vehicleModel')" align="center" prop="vehicleTypeId"
                :formatter="getVehicleTypeAttribute" />
            <el-table-column :label="$t('feedback.specification.documentType')" align="center" prop="documentType" />
            <el-table-column :label="$t('feedback.specification.documentAddress')" align="center" prop="documentAddress" />
            <el-table-column :label="$t('feedback.specification.status')" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                        @change="handleEnableChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column :label="$t('common.table.operate')" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 1)"
                        v-hasPermi="['system:manual:edit']">{{ $t('common.button.edit') }}</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row, 2)"
                        v-hasPermi="['system:manual:edit']">{{ $t('common.button.detail') }}</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDownload(scope.row)"
                        v-hasPermi="['system:manual:edit']">{{ $t('common.button.download') }}</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:manual:remove']">{{ $t('common.button.delete') }}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改车辆说明书对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :disabled="disabled" :rules="rules" label-width="80px">
                <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                    <el-select v-model="form.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')"
                        :style="{ width: '100%' }">
                        <el-option v-for="dict in typesList" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文件类型" prop="documentType">
                    <el-select v-model="form.documentType" :style="{ width: '100%' }">
                        <el-option v-for="dict in dict.type.specification_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件地址" prop="documentAddress">
                    <el-upload class="upload-demo" drag accept=".pdf,.doc,.docx" :limit="1" :headers="upload.headers"
                        :file-list="fileList" :action="upload.url" multiple :on-success='handleFileSuccess'
                        :on-progress="handleFileUploadProgress" :data="form" :auto-upload="true">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">{{ $t('version.firmware.uploadText') }}
                            <em>{{ $t('version.firmware.clickUpload') }}</em>
                        </div>
                        <!-- <div class="el-upload__tip" slot="tip" style="color: red;">
                            {{ $t('version.firmware.uploadCheck') }}
                        </div> -->
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import { getToken } from "@/utils/auth";
import { listType } from "@/api/vehicle/type/data";
import { listManual, getManual, delManual, addManual, updateManual, changeStatus } from "@/api/specification/data";

export default {
    name: "Specification",
    dicts: ['specification_type'],
    data() {
        return {
            disabled: false,
            fileList: [],
            // 非多个禁用
            multiple: true,
            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                url: process.env.VUE_APP_BASE_API + "/device/firmware/version/upload",
            },
            typesList: [],
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 车辆说明书表格数据
            manualList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                vehicleTypeId: undefined,
                documentType: undefined,
                documentAddress: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                specificationId: [
                    { required: true, message: "说明ID不能为空", trigger: "blur" }
                ],
                vehicleTypeId: [
                    { required: true, message: "关联车型ID不能为空", trigger: "blur" }
                ],
                documentType: [
                    { required: true, message: "文档类型：WORD/ PDF不能为空", trigger: "change" }
                ],
                // documentAddress: [
                //     { required: true, message: "文件地址不能为空", trigger: "blur" }
                // ],
            }
        };
    },
    created() {
        this.getList();
        this.getTypeList();
    },
    methods: {
        getVehicleTypeAttribute(row) {
            const type = this.typesList.find(item => item.value === row.vehicleTypeId);
            return type ? type.label : '';
        },
        getTypeList() {
            listType().then(response => {
                this.typesList = response.rows.map(item => {
                    return {
                        label: item.typeName,
                        value: item.id
                    }
                })
            })
        },
        /** 查询车辆说明书列表 */
        getList() {
            this.loading = true;
            listManual(this.queryParams).then(response => {
                this.manualList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                specificationId: undefined,
                vehicleTypeId: undefined,
                documentType: undefined,
                documentAddress: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined,
                originalFileName: undefined
            };
            this.fileList = [];
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.specificationId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加车辆说明书";
        },
        /** 修改按钮操作 */
        handleUpdate(row, val) {
            this.loading = true;
            this.reset();
            if (val === 2) {
                this.disabled = true;
            }
            const specificationId = row.specificationId || this.ids
            getManual(specificationId).then(response => {
                this.loading = false;
                this.form = response.data;
                const uploadData = {
                    name: response.data.originalFileName,
                    url: response.data.documentAddress
                }
                this.fileList.push(uploadData)
                this.open = true;
                this.title = "修改车辆说明书";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.specificationId != null) {
                        updateManual(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addManual(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const specificationIds = row.specificationId || this.ids;
            this.$modal.confirm('是否确认删除车辆说明书编号为"' + specificationIds + '"的数据项？').then(() => {
                this.loading = true;
                return delManual(specificationIds);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/manual/export', {
                ...this.queryParams
            }, `manual_${new Date().getTime()}.xlsx`)
        },

        // 下面是文件上传功能
        handleFileSuccess(response, file) {
            this.form.documentAddress = response;
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
            this.form.fileSize = file.size
            this.form.originalFileName = file.name
        },
        handleDownload(row) {
            var link = document.createElement('a');
            link.href = row.documentAddress;
            link.download = row.originalFileName; // 可选，设置下载时保存的文件名
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        handleDetail(row, type) {
            window.location.href = row.documentAddress;
        },
        handleEnableChange(row) {
            let text = row.status === 0 ? this.$t('common.operate.tip.stop') : this.$t('common.operate.tip.enable');
            this.$modal.confirm(
                this.$t('common.message.tip.confirm', {
                    operate: text,
                    name: this.$t('version.firmware.isEnable'),
                    data: row.versionName
                })
            ).then(function () {
                return changeStatus({ specificationId: row.specificationId, vehicleTypeId: row.vehicleTypeId });
            }).then(() => {
                this.$modal.msgSuccess(text + this.$t('common.operate.tip.success'));
                this.getList();
            }).catch(function () {
                row.status = row.status === 0 ? 1 : 0;
            });
        }

    }
};
</script>
  